﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Security.Cryptography.X509Certificates;
using Newtonsoft.Json;
using Cloud.Core.Model;
using Cloud.Core.Response;
using Cloud.Core.AuthUser;
using Microsoft.EntityFrameworkCore.Internal;
using Cloud.Core.Bizlogic;
using Microsoft.AspNetCore.Cors;
using Cloud.Core.ModelSearch;
using System.Collections;
using Senparc.Weixin.WxOpen.AdvancedAPIs.Sns;
using static Cloud.Core.wechat.WeChat;
using System.Net.Http;
using System.Net;
using Senparc.NeuChar.NeuralSystems;

namespace Cloud.Core.Controllers
{
    /// <summary>
    /// 用户管理
    /// </summary> 
    [Route("api/v1/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly CloudDataBase _context;
        private readonly ModOperate.Mod _thisModel = ModOperate.Mod.MBasicInfo;
        private readonly HttpClient _httpClient;
        public UserController ( CloudDataBase context, HttpClient httpClient )
        {
            _context = context;
            _httpClient = httpClient;
        }

        #region base
        #region 用户登录
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="loginid"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        [Route("SignIn")]
        [HttpPost]
        public async Task<JsonResponse<JsonLoginResponse<User>>> SignIn ( [FromHeader] string Authorization, [FromBody] sSignIn sSign )
        {
            var _character = Online.GetLoginInfo(Authorization);
            var response = new JsonResponse<JsonLoginResponse<User>>();
            //var response = Online.AuthUser<JsonResponse<JsonLoginResponse<User>>>(_thisModel, ModOperate.Operate.Search, _character);
            //if (response.Status != ResponseStatus.Success)
            //{
            //    return response;
            //}
            var user = await _context.User.FirstOrDefaultAsync(t => t.LoginId == sSign.loginid && t.Password == sSign.pwd).ConfigureAwait(false);
            if (user == null)
            {
                response.Status = ResponseStatus.NullData;
                response.Msg = "登录失败";
                await new LoggerWriteen().writeAsync(new Log(Log.OperateType.登录, response.Msg), RouteData.Values.Values.Join(",")).ConfigureAwait(false);
            }
            else
            {
                var loginResponse = new JsonLoginResponse<User>();
                string guid = Online.LogIn(user);
                loginResponse.Data = user;
                loginResponse.accessToken = guid;
                response.Data = loginResponse;
                response.Msg = "登录成功";
                response.Status = ResponseStatus.Success;
                await new LoggerWriteen().writeAsync(new Log(Log.OperateType.登录, response.Msg), RouteData.Values.Values.Join(","));
            }
            await new LoggerWriteen().writeAsync(new Log(Log.OperateType.操作, response.Msg), RouteData.Values.Values.Join(","));
            return response;
        }
        #endregion

        #region 获取用户信息
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Route("GetById")]
        [HttpGet]
        public async Task<JsonResponse<User>> GetById ( [FromHeader] string Authorization, string id )
        {

            var _character = Online.GetLoginInfo(Authorization);
            var response = Online.AuthUser<User>(_thisModel, ModOperate.Operate.Search, _character);
            //if (response.Status != ResponseStatus.Success)
            //{
            //    return response;
            //}
            response.Data = await _context.User.FirstOrDefaultAsync(t => t.Id == Convert.ToDouble(id)).ConfigureAwait(false);

            if (response.Data == null)
            {
                response.Status = ResponseStatus.NullData;
                response.Msg = "无用户数据";
            }
            else
            {
                response.Status = ResponseStatus.Success;
                response.Msg = "查询成功";
            }
            return response;
        }
        /// <summary>
        /// 获取openid
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        //[Route("GetOpenid")]
        //[HttpGet]
        //public JsCode2JsonResult GetOpenid ( string code)
        //{
        //    try
        //    {
        //        JsCode2JsonResult jsonResult = new JsCode2JsonResult();
        //        jsonResult = SnsApi.JsCode2Json("wx80a16c6d4b037812", "2a0b76b4065bcc29e2a3f8e7b2bd5228", code);

        //        return jsonResult;
        //    }
        //    catch (Exception ex)
        //    {
        //        return null;
        //    }

        //}

        #endregion

        #region 获取用户openId
        /// <summary>
        /// 获取微信用户openid
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpGet("GetNewOpenid")]
        public async Task<JsonResponse<string>> GetNewOpenid ( string code )
        {
            try
            {
                // 微信接口 URL
                string url = $"https://api.weixin.qq.com/sns/jscode2session?" +
                             $"appid=wx80a16c6d4b037812&" + // 替换为您的 AppID
                             $"secret=2a0b76b4065bcc29e2a3f8e7b2bd5228&" + // 替换为您的 AppSecret
                             $"js_code={code}&" +
                             $"grant_type=authorization_code";

                // 发起 HTTP 请求
                HttpResponseMessage response = await _httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();

                // 解析返回结果
                string responseBody = await response.Content.ReadAsStringAsync();

                var result = Newtonsoft.Json.JsonConvert.DeserializeObject<JsCode2JsonResult>(responseBody);

                // 如果有错误码，则返回错误信息
                //if (!string.IsNullOrEmpty(result.Errcode))
                //{
                //    return BadRequest(new { error = result.Errmsg });
                //}

                // 返回 openid 和 session_key

                return new JsonResponse<string>
                {
                    Data = result.openid,
                    Msg = "获取openid成功",
                    Status = ResponseStatus.Success

                };
            }
            catch (Exception ex)
            {
                return new JsonResponse<string>
                {
                    Data = "",
                    Msg = "请求失败",
                    Status = ResponseStatus.RequestError
                };
            }
        }

        #endregion

        #region 获取分页信息
        /// <summary>
        /// 获取全部用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Route("GetList")]
        [HttpPost]
        public async Task<JsonResponse<DataList<object>>> GetList ( [FromHeader] string Authorization, sPage sUser )
        {
            var _character = Online.GetLoginInfo(Authorization);
            var response = Online.AuthUser<DataList<object>>(_thisModel, ModOperate.Operate.Search, _character);
            //if (response.Status != ResponseStatus.Success)
            //{
            //    return response;
            //}+

            response.Data = new DataList<object>();
            new Helper().sPageNew(sUser);
            var listQuery = _context.User.Where(t => t.Id >= 0 && t.Id <= int.MaxValue);
            if (!string.IsNullOrEmpty(sUser.Field1))
            {
                listQuery = listQuery.Where(t => t.Phone.Contains(sUser.Field1));
            }
            if (!string.IsNullOrEmpty(sUser.Field2))
            {
                listQuery = listQuery.Where(t => t.LoginId.Contains(sUser.Field2));
            }
            response.Data.Total = await listQuery.CountAsync().ConfigureAwait(false);
            //var list = await listQuery
            //       .OrderByDescending(t => t.Id)
            //       .Skip((int)sUser.PageIndex * (int)sUser.PageSize)
            //       .Take((int)sUser.PageSize)
            //       .ToArrayAsync()
            //       .ConfigureAwait(false);
            var list = listQuery.Skip((int)sUser.PageIndex * (int)sUser.PageSize)
                   .Take((int)sUser.PageSize).ToArray();
            //添加部门名称
            //var list = await listQuery.Join(_context.Department,//listQuery集合要连接的Department实体集合
            //            user => user.DeptId,//左表要连接的键
            //            dept => dept.Id + "",//右表要连接的键
            //            (user, dept) => new LoggerWriteen().CombinedData<User, Department>(
            //               user,
            //               dept,
            //               new Dictionary<string, string>() { { "Name", "deptName" }, { "parentIdPath", "parentIdPath" }, { "Sid", "deptRemark" } }
            //               )
            //            )
            //       //.OrderByDescending(t => t)
            //       .Skip((int)sUser.PageIndex * (int)sUser.PageSize)
            //       .Take((int)sUser.PageSize)
            //       .ToArrayAsync()
            //       .ConfigureAwait(false);

            response.Data.Count = list.Length;

            response.Data.List = list;
            response.Msg = "查询成功";
            response.Status = ResponseStatus.Success;
            return response;
        }
        #endregion

        #region 用户添加
        /// <summary>
        /// 用户添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [Route("UserAdd")]
        [HttpPost]
        public async Task<JsonResponse> UserAdd ( [FromHeader] string Authorization, User entity = null )
        {
            var _character = Online.GetLoginInfo(Authorization);
            var response = Online.AuthUser(_thisModel, ModOperate.Operate.Add, _character);
            //if (response.Status != ResponseStatus.Success)
            //{
            //    return response;
            //}            

            if (entity == null)
            {
                response.Msg = "参数为空";
                response.Status = ResponseStatus.ParameterError;
            }
            if (entity.LoginId == "" || entity.Password == "" && entity.UserType == "")
            {
                response.Msg = "用户名、用户类型、密码不允许为空！";
                response.Status = ResponseStatus.ParameterError;
                return response;
            }
            var data = await _context.User.FirstOrDefaultAsync(t => t.LoginId == entity.LoginId).ConfigureAwait(false);
            if (data != null)
            {
                response.Msg = "添加失败,该用户名已存在";
                response.Status = ResponseStatus.MultipleData;
                await new LoggerWriteen().writeAsync(new Log(Log.OperateType.异常, response.Msg), RouteData.Values.Values.Join(","));
                return response;
            }

            var arr = _context.User.Select(t => t.Id).ToArray();
            ulong maxNum = 0;
            if (arr.Length > 0)
            {
                maxNum = arr.Max();
            }
            entity.Id = maxNum + 1;
            entity.CreateDate = DateTime.Now;
            entity.ModifyDate = DateTime.Now;
            _context.Set<User>().Add(entity);
            int num = await _context.SaveChangesAsync().ConfigureAwait(false);
            if (num > 0)
            {
                response.Msg = "用户添加成功";
                response.Status = ResponseStatus.Success;
            }
            else
            {
                response.Msg = "用户添加失败";
                response.Status = ResponseStatus.ParameterError;
            }
            string et = response.Msg + "-实体内容:" + new Helper().ObjectToJson(entity);
            await new LoggerWriteen().writeAsync(new Log(Log.OperateType.操作, et), RouteData.Values.Values.Join(","));
            return response;
        }
        #endregion

        #region 用户编辑
        /// <summary>
        /// 用户编辑 
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("UserUpdate")]
        public async Task<JsonResponse> UserUpdate ( [FromHeader] string Authorization, User entity = null )
        {
            var _character = Online.GetLoginInfo(Authorization);
            var response = Online.AuthUser(_thisModel, ModOperate.Operate.Add, _character);
            //if (response.Status != ResponseStatus.Success)
            //{
            //    return response;
            //}
            if (entity == null)
            {
                response.Msg = "参数为空";
                response.Status = ResponseStatus.ParameterError;
                return response;
            }
            // var data = await _context.User.FirstOrDefaultAsync(t => t.Id == Convert.ToDouble(entity.Id)).ConfigureAwait(false);
            var dataCount = _context.Set<User>().Where(t => t.Id == Convert.ToDouble(entity.Id)).Count();
            if (dataCount == 0)
            {
                response.Msg = "修改失败,数据不存在";
                response.Status = ResponseStatus.NullData;
                return response;
            }
            _context.Set<User>().Update(entity);
            int num = _context.SaveChanges();
            if (num > 0)
            {
                response.Msg = "用户修改成功";
                response.Status = ResponseStatus.Success;
            }
            else
            {
                response.Msg = "用户修改失败";
                response.Status = ResponseStatus.ProcessFail;
            }
            string et = response.Msg + "-修改数据:" + new Helper().objToJson(entity);
            await new LoggerWriteen().writeAsync(new Log(Log.OperateType.操作, et), RouteData.Values.Values.Join(","));
            return response;
        }

        #endregion

        #region 用户删除
        /// <summary>
        /// 用户删除 
        /// </summary>
        /// <param name="aaa"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("UserDel")]
        public async Task<JsonResponse> UserDel ( [FromHeader] string Authorization, string ids = null )
        {
            var _character = Online.GetLoginInfo(Authorization);
            var response = Online.AuthUser(_thisModel, ModOperate.Operate.Add, _character);
            //if (response.Status != ResponseStatus.Success)
            //{
            //    return response;
            //}
            if (ids.Length == 0)
            {
                response.Msg = "参数为空";
                response.Status = ResponseStatus.ParameterError;
            }

            string[] arr = ids.TrimEnd(',').Split(',');
            ulong[] barr = new ulong[arr.Length];
            for (int i = 0 ; i < arr.Length ; i++)
            {
                barr[i] = Convert.ToUInt64(arr[i]);
            }
            var users = _context.User.Where(c => barr.Contains(c.Id));

            var dataCount = users.Count();
            if (dataCount == 0)
            {
                response.Msg = "数据不存在,不允许删除";
                response.Status = ResponseStatus.NullData;
                return response;
            }

            string delArr = new Helper().objToJson(users);
            _context.User.RemoveRange(users);

            int num = _context.SaveChanges();
            if (num > 0)
            {
                response.Msg = "用户删除成功";
                response.Status = ResponseStatus.Success;
            }
            else
            {
                response.Msg = "用户删除失败";
                response.Status = ResponseStatus.ParameterError;
            }
            delArr = response.Msg + "-删除集合:" + delArr;
            await new LoggerWriteen().writeAsync(new Log(Log.OperateType.操作, delArr), RouteData.Values.Values.Join(","));
            return response;
        }
        #endregion

        #region 修改密码
        /// <summary>
        /// 修改密码 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="NewPwd"></param>
        /// <param name="NewPwdAgain"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("ChangePwd")]
        public async Task<JsonResponse> ChangePwd ( [FromHeader] string Authorization, string id = null, string NewPwd = null, string NewPwdAgain = null )
        {
            var _character = Online.GetLoginInfo(Authorization);
            var response = Online.AuthUser(_thisModel, ModOperate.Operate.Add, _character);
            //if (response.Status != ResponseStatus.Success)
            //{
            //    return response;
            //}

            if (id == null || NewPwd == null || NewPwdAgain == null)
            {
                response.Msg = "参数为空";
                response.Status = ResponseStatus.ParameterError;
                return response;
            }
            if (NewPwd != NewPwdAgain)
            {
                response.Msg = "密码输入不一致！";
                response.Status = ResponseStatus.ParameterError;
                return response;
            }
            var tt = _context.Set<User>().Where(c => c.Id == Convert.ToDouble(id)).First();
            tt.Password = NewPwd;
            _context.Set<User>().Update(tt);
            int num = _context.SaveChanges();
            if (num > 0)
            {
                response.Msg = "用户密码修改成功";
                response.Status = ResponseStatus.Success;
            }
            else
            {
                response.Msg = "用户密码修改失败";
                response.Status = ResponseStatus.ParameterError;
            }
            await new LoggerWriteen().writeAsync(new Log(Log.OperateType.操作, response.Msg), RouteData.Values.Values.Join(","));

            return response;
        }
        #endregion

        #endregion
    }
}
